package com.umeox.phone.base;

import static android.telephony.TelephonyManager.EXTRA_INCOMING_NUMBER;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeox.moto.common.utils.AndroidUtils;
import com.umeox.phone.BuildConfig;
import com.umeox.phone.R;
import com.umeox.phone.receiver.BasePhoneStateListener;
import com.umeox.phone.util.CacheUtils;
import com.umeox.watch.moto.dataservice.DataProvider;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import uk.co.chrisjenx.calligraphy.CalligraphyConfig;

public class BaseApplication extends Application {

    public static List<Activity> mList = new LinkedList<>();
    private static BaseApplication instance;
    private BasePhoneStateListener mPhoneStateListener;

    public static BaseApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        CrashReport.UserStrategy userStrategy = new CrashReport.UserStrategy(this);
        userStrategy.setAppChannel(BuildConfig.FLAVOR + "-" + AndroidUtils.getDeviceId());
        CrashReport.initCrashReport(this, "a018aa68d5", false, userStrategy);

        CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                .setDefaultFontPath("fonts/RobotoCondensed-Regular.ttf")
                .setFontAttrId(R.attr.fontPath)
                .build()
        );
        instance = this;
        DataProvider.initialize(this);
        CacheUtils.setCallStateCalling(this, false);
        mPhoneStateListener = BasePhoneStateListener.getInstance(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            registerReceiver(new PhoneReceiver(), new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED));
        } else {
            TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
            telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }

        DataProvider.ContactProvider.registerContentObserver(true, mContentObserver);
    }

    List<String> mIconUrl = new ArrayList<>();
    ContentObserver mContentObserver = new ContentObserver(null) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            final List<ContentValues> contacts = DataProvider.getContacts();
            if (contacts != null) {

                for (ContentValues contact : contacts) {
                    final String url = contact.getAsString(DataProvider.ContactProvider.PHOTO_URL);
                    if (mIconUrl.contains(url)) return;
                    GlideApp.with(BaseApplication.this).asDrawable().load(url).into(new CustomTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            mIconUrl.add(url);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {
                        }
                    });
                }


            }


        }
    };

    // add Activity
    public void addActivity(Activity activity) {
        mList.add(activity);
    }

    public class PhoneReceiver extends BroadcastReceiver {
        String[] stateArr = {TelephonyManager.EXTRA_STATE_IDLE, TelephonyManager.EXTRA_STATE_RINGING, TelephonyManager.EXTRA_STATE_OFFHOOK};

        @Override
        public void onReceive(Context context, Intent intent) {
            if (CacheUtils.isCallMonitoring(context)) {
                return;
            }
            final String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

            final int index = Arrays.asList(stateArr).indexOf(state);
            final String number = intent.getStringExtra(EXTRA_INCOMING_NUMBER);
            mPhoneStateListener.onCallStateChanged(index, number);
        }
    }
}
